$(document).ready(function(){
    setNowAll();

    $("#ay").change(function(){
        var selectedYear = $("#ay").val();
        if (selectedYear == new Date().getFullYear()) {
            setNowAll();
        }else{
            $("#am, #ad").html("");
            for(var month = 1; month <= 12; month ++){
                var m = document.createElement("option");
                m.value = month;
                m.innerHTML = month;
                $("#am").append(m);
            }
            for(var day = 1; day <= 31; day ++){
                var d = document.createElement("option");
                d.value = day;
                d.innerHTML = day;
                $("#ad").append(d);
            }
        }
    })

    $("#am").change(function(){
        var selectedYear = parseInt($("#ay").val());
        var selectedMonth = parseInt($("#am").val());

        $("#ad").html("");
        if (selectedYear == new Date().getFullYear() && selectedMonth == new Date().getMonth() + 1) {
            for(var i = new Date().getDate(); i <= getDaysInMonth(selectedMonth, selectedYear); i ++){
                var d = document.createElement("option");
                d.value = i;
                d.innerHTML = i;
                $("#ad").append(d);

            }
        }
        else{
            for(var i = 1; i <= getDaysInMonth(selectedMonth, selectedMonth); i ++){
                var d = document.createElement("option");
                d.value = i;
                d.innerHTML = i;
                $("#ad").append(d);
            }
        }
    })

    $("#button").click(function(){
        if($("#applyName").val() === ""){
            alert("请填写完整信息!");
        }else{
            $("#form_submit").attr("action", "../php/apply_night.php");
        }
    })
})

function setNowAll () {
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var day = d.getDate();

    $("#ay, #am, #ad").html("");
    for(var i = 0; i < 2; i ++){
        var y = document.createElement("option");
        y.value = year + i;
        y.innerHTML = year + i;
        $("#ay").append(y);
    }
    for(var i = month; i <= 12; i ++){
        var m = document.createElement("option");
        m.value = i;
        m.innerHTML = i;
        $("#am").append(m);
    }
    for(var i = day; i < getDaysInMonth(month, year); i ++){
        var d = document.createElement("option");
        d.value = i;
        d.innerHTML = i;
        $("#ad").append(d);
    }
}

function getDaysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}